package com.cloud.cloudshop.task;

import com.alibaba.fastjson.JSON;
import com.cloud.cloudshop.provider.RabbitOrderSender;
import com.cloud.cloudshop.shop.constant.Constants;
import com.cloud.cloudshop.shop.dao.OrderMessageDao;
import com.cloud.common.entity.OrderEntity;
import com.cloud.common.entity.OrderMessageEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 */
@Component
@Slf4j
public class RetryMessageTasker {

    @Autowired
    private RabbitOrderSender rabbitOrderSender;

    @Autowired
    private OrderMessageDao orderMessageDao;

    @Scheduled(initialDelay = 5000, fixedDelay = 10000)
    public void reSend() {
        System.out.println("-----------定时任务开始-----------");
        //pull status = 0 and timeout message
        List<OrderMessageEntity> list = orderMessageDao.query4StatusAndTimeoutMessage();
        list.forEach(messageLog -> {
            if (messageLog.getTryCount() >= 3) {
                log.info("---------> 重试次数大于3次 ，需要人工介入 messageId :" + messageLog.getMessageId());
                //update fail message
                orderMessageDao.changeBrokerMessageLogStatus(messageLog.getMessageId(), Constants.ORDER_SEND_FAILURE, new Date());
            } else {
                log.info("---------> 消息投递失败，重新投递 messageId :" + messageLog.getMessageId());
                // resend
                orderMessageDao.update4ReSend(messageLog.getMessageId(), new Date());
                OrderEntity reSendOrder = JSON.parseObject(messageLog.getMessage(), OrderEntity.class);
                try {
                    rabbitOrderSender.sendOrderByDirectExchange(reSendOrder);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}

